// pages/home/home.js
import { getChannels, getArticles, getAllChannels } from '../../api/home'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    showPopup: false,
    channelList: [],
    allChannelList: [],
    savChannelList: [],
    refresherStatus: false,
    params: {
      channel_id: 0,
      with_top: 1,
      timestamp: null,
    },
    articleList: [],
    editChannel: 0,
    dateFormat: () => { },
    // 触底节流
    timer: null,
  },
  /**
   * page methods
   */
  showPopup() {
    this.setData({showPopup:true})
  },
  closePopup() {
    this.setData({showPopup:false})
  },
  async refresherTab() {
    await this.getArticleList()
    this.setData({ refresherStatus: false })
  },
  changeEdit() {
    this.setData({editChannel:!this.data.editChannel})
  },
  navigatorTo(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/article/article?id=${id}`
    })
  },
  setSavChannels() {
    const arr = []
    let flag = true
    this.data.allChannelList.forEach(i => {
      this.data.channelList.forEach(k => {
        if (i.id === k.id) flag = false
      })
      if (flag) arr.push(i)
      flag = true
    })
    this.setData({
      savChannelList: arr
    })
  },
  /**
   * api-methods-define
   */
  async getChannelList() {
    const {data} = await getChannels()
    this.setData({channelList:data.channels})
    this.selectComponent('#tabs').resize();
  },
  async getAllChannelList() {
    if(!this.data.channelList.length) return
    const {data} = await getAllChannels()
    this.setData({allChannelList:data.channels})
    this.setSavChannels()
  },
  async getArticleList() {
    const obj = this.data.params
    obj.timestamp = new Date().getTime()
    const {data} = await getArticles(obj)
    this.setData({
      articleList:data.results
    })
  },
  getChannelID(e) {
    this.setData({'params.channel_id':e.detail.index})
    this.getArticleList()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getChannelList()
    this.getArticleList()
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    /* wx.getStorage({
      key: 'user-info',
      success({data}) {
        console.log(JSON.parse(data))
      }
    }) */
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.timer) return
    const obj = this.data.params
    obj.timestamp = new Date().getTime()
    this.data.timer = setTimeout(async _ => {
      const { data } = await getArticles(obj)
      clearTimeout(this.data.timer)
      this.setData({
        articleList: [...this.data.articleList, ...data.results],
        timer: null
      })
    }, 6000)
    this.setData({timer:this.data.timer})
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})